"use client";
import { useEffect, useRef, useState } from "react";

type Props = {
  src: string;
  setSrc(file: File): void;
};

const FileUploader = ({ src, setSrc }: Props) => {
  const [localSrc, setLocalSrc] = useState<string>("");
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setLocalSrc(src);
  }, [src]);

  const handleClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };
  const toBase64 = (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = reject;
    });

  const handleFileChange = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      setSrc(files[0]);
      setLocalSrc(await toBase64(files[0]));
    }
  };

  const getSrc = () => {
    if (src.length > 0) {
      return `${!localSrc.includes("data:image/jpeg;base64,") ? "data:image/jpeg;base64," : ""}${localSrc}`;
    } else if (localSrc.length < 1) return "/images/no_photo.jpg";
    else {
      return `${!localSrc.includes("data:image/jpeg;base64,") ? "data:image/jpeg;base64," : ""}${localSrc}`;
    }
  };

  return (
    <div>
      <img src={getSrc()} onClick={handleClick} className="itemPhoto" />
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: "none" }}
        onChange={handleFileChange}
      />
    </div>
  );
};

export default FileUploader;
1;
